/*******************************************************************
 * Copyright (c) 2013 珠海比特讯科技有限公司. All rights reserved.
 * （1）软件的版权将受到法律保护，不允许非经授权的使用；
 * （2）未经版权所有人授权，任何人不得修改、复制和传播软件源代码、图片及其它资源等；
 * （3）未经版权所有人授权，不允许对软件进行修改；
 * （4）未经版权所有人授权，不允许在该软件的基础上开发新的软件；
 * （5）珠海比特讯科技有限公司拥有最终解释权
 *******************************************************************/
package youxiao.bytezon.configs.security.auth;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import youxiao.bytezon.configs.security.models.GrantedAuthorityImpl;
import youxiao.bytezon.constants.AuthorizationConst;
import youxiao.bytezon.models.Teacher;
import youxiao.bytezon.repositories.TeacherRepository;

//自定义身份认证验证组件
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	@Autowired TeacherRepository teacherRepository;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// 获取认证的用户名 & 密码
		String name = authentication.getName();
		String password = authentication.getCredentials().toString();

		Teacher teacher = teacherRepository.findByPhone(name);
		PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		
		// 认证逻辑
		if (teacher != null && passwordEncoder.matches(password, teacher.getPassword())) {
			// 这里设置权限和角色
			ArrayList<GrantedAuthority> authorities = new ArrayList<>();
			authorities.add(new GrantedAuthorityImpl(AuthorizationConst.READ_TEACHER_INFO));
			// 生成令牌
			Authentication auth = new UsernamePasswordAuthenticationToken(name, teacher.getPassword(), authorities);
			return auth;
		} else {
			throw new BadCredentialsException("密码错误~");
		}
	}

	// 是否可以提供输入类型的认证服务
	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}
}
